package com.photography.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.photography.entity.User;
import com.photography.entity.Photographers;
import com.photography.exception.CustomException;
import com.photography.service.UserService;
import com.photography.service.PhotographersService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtInterceptor.class);

    @Resource
    private UserService userService;

    @Resource
    private PhotographersService photographersService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // Bypass JWT check for image files
        String uri = request.getRequestURI();
        if (uri.startsWith("/api/files/")) {
            log.info("放行图片请求");
            return true;
        }

        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            log.info("放行Options");
            return true;
        }

        //1.获取token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            token = request.getParameter("token");
        }
        //2.认证
        if (StrUtil.isBlank(token)) {
            throw new CustomException("无token，重新登录");
        }

        try {
            // 验证token是否过期
            JWT.decode(token).getExpiresAt();

            //获取token中的id
            String id = JWT.decode(token).getAudience().get(0);

            // 尝试作为用户验证
            User user = userService.getById(Integer.parseInt(id));
            if (user != null) {
                // 验证token签名
                JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                verifier.verify(token);
                return true;
            }

            // 尝试作为摄影师验证
            Photographers photographer = photographersService.getById(Integer.parseInt(id));
            if (photographer != null) {
                // 验证token签名
                JWTVerifier verifier = JWT.require(Algorithm.HMAC256(photographer.getPassword())).build();
                verifier.verify(token);
                return true;
            }

            throw new CustomException("用户不存在");
        } catch (TokenExpiredException e) {
            log.error("token已过期", e);
            throw new CustomException("token已过期，请重新登录");
        } catch (IndexOutOfBoundsException e) {
            String errMsg = "token中未包含有效的ID";
            log.error(errMsg + ",token=" + token, e);
            throw new CustomException(errMsg);
        } catch (NumberFormatException e) {
            String errMsg = "token中的ID不是有效的整数";
            log.error(errMsg + ",token=" + token, e);
            throw new CustomException(errMsg);
        } catch (Exception e) {
            String errMsg = "token验证失败";
            log.error(errMsg + ",token=" + token, e);
            throw new CustomException(errMsg);
        }
    }
}